export default {
	props: {
		// 录音时长 秒
		audioMaxDuration: {
			type: Number,
			default: 30
		},
	},
	data() {
		return {
			audio: [],
			audioPopupShow: false,
			audioRecorderManager: null, // 录音管理实例
			audioRecordCount: 0, // 录音时长计数
			audioRecording: false, // 是否正在录音
			audioPlaying: false // 是否正在播放录音
		}
	},
	beforeDestroy() {
		if (this.audioPlaying) { // 如果该组件正在播放，则销毁
			this.$audioController.destroyAudio();
		}
		if (this.audioRecording) { // 如果该组件正在录音，则停止录音
			this.audioRecorderManager.stop();
		}
	},
	methods: {
		// 播放录音
		playThisAudio(src) {
			this.$audioController.playAudio(this, src);
		},
		// 弹窗弹起
		addAudio() {
			if (this.disabled) return;
			if (this.audio.length > 0) {
				uni.showToast({
					title: '请先删除已有录音',
					icon: 'none'
				})
				return;
			}
			this.audioRecordCount = 0;
			this.audioPopupShow = true;
		},
		// 弹窗关闭
		closeAudio() {
			this.audioPopupShow = false;
		},
		// 开始录制
		startRecordAudio() {
			if (!this.audioRecorderManager) { // 创建录音实例
				this.audioRecorderManager = uni.getRecorderManager();
			}
			if (this.audioRecording) { // 正在录音则停止录音
				this.audioRecording = false;
				this.audioRecorderManager.stop();
				return;
			}
			// 开始
			this.audioRecorderManager.start({
				duration: this.audioMaxDuration * 1000,
				format: 'mp3'
			});
			this.$w.permission('record', () => {
				this.audioRecording = true;
				// 计时，超过最大录音限制则停止
				let timer = setInterval(() => {
					this.audioRecordCount++;
					if (this.audioRecordCount == this.audioMaxDuration) {
						this.audioRecording = false;
						this.audioRecorderManager.stop();
					}
				}, 1000)
				// 监听：录音停止
				this.audioRecorderManager.onStop(res => {
					clearInterval(timer);
					if (this.audioRecording) return; // 非正常停止录音，则不执行上传
					this.uploadAudio(res.tempFilePath); // 上传录音
				});
			});
		},
		// 上传录音
		async uploadAudio(src) {
			let header = {
				// 'Content-Type': 'multipart/form-data',
				// #ifndef H5
				'Cookie': this.$http.sessionId
				// #endif
			};
			if (this.$http.token)
				header[this.$http.token.header] = this.$http.token.token;
			if (this.checkToken) {
				await this.$http.checkToken(header, () => {
					uni.showToast({
						title: '登录信息已失效',
						icon: 'none'
					})
					uni.reLaunch({
						url: '/pages/login/login'
					});
					this.$http.logout();
				})
			}
			uni.showLoading({
				title: '请稍候……',
				mask: true
			})
			let result = await uni.uploadFile({
				url: this.url.replace('$type', 'audio'),
				filePath: src,
				// name: 'file',
				header
			});
			if (result[1]?.statusCode == 200) {
				this.audio.push({
					previewSrc: src,
					...JSON.parse(result[1].data).message
				})
				this.closeAudio(); // 关闭弹窗
				uni.hideLoading(); // 消失loading
			} else {
				uni.hideLoading();
				uni.showToast({
					title: '录音失败',
					icon: 'none'
				})
				this.closeAudio();
			}
			this.change();
		}
	}
}